/*工具方法*/
export default {
    /*保存session*/
    setSession: function (key, value) {
        sessionStorage.setItem(key, JSON.stringify(value));
    },
    /*获取session*/
    getSession: function (key) {
        return JSON.parse(sessionStorage.getItem(key));
    },
    /*保存localStorage*/
    setStroage: function (key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    },
    /*获取localStorage */
    getStroage: function (key) {
        return JSON.parse(localStorage.getItem(key));
    },
    //获取路径参数
    getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
	//时间格式化
	dateFormat(fmt, date) {
	    let ret;
	    const opt = {
	        "Y+": date.getFullYear().toString(),        // 年
	        "m+": date.getMonth()<9?"0"+((date.getMonth() + 1).toString()):(date.getMonth() + 1).toString(),     // 月
	        "d+": date.getDate()<9?"0"+date.getDate().toString():date.getDate().toString(),            // 日
	        "H+": date.getHours()<9?"0"+date.getHours().toString():date.getHours().toString(),           // 时
	        "M+": date.getMinutes()<9?"0"+date.getMinutes().toString():date.getMinutes().toString(),         // 分
	        "S+": date.getSeconds()<9?"0"+date.getSeconds().toString():date.getSeconds().toString()          // 秒
	        // 有其他格式化字符需求可以继续添加，必须转化成字符串
	    };
	    for (let k in opt) {
	        ret = new RegExp("(" + k + ")").exec(fmt);
	        if (ret) {
	            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
	        };
	    };
	    return fmt;
	},
	
	//封装树结构
	handleTree(data, id, parentId, children, rootId) {
		id = id || 'id'
		parentId = parentId || 'parentId'
		children = children || 'children'
		rootId = rootId || 0
		//对源数据深度克隆
		const cloneData = JSON.parse(JSON.stringify(data))
		//循环所有项
		const treeData =  cloneData.filter(father => {
		  let branchArr = cloneData.filter(child => {
			//返回每一项的子级数组
			return father[id] === child[parentId]
		  });
		  branchArr.length > 0 ? father.children = branchArr : '';
		  //返回第一层
		  return father[parentId] === rootId;
		});
		return treeData != '' ? treeData : data;
	  }
}
